package com.mentalhealthplatform.teacherV2.service;

import com.mentalhealthplatform.appModels.FamilyMessage;
import com.mentalhealthplatform.appModels.Student;
import com.mentalhealthplatform.teacherV2.repository.FamilyMessageRepositoryV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class FamilyMessageServiceV2 {

    @Autowired
    private FamilyMessageRepositoryV2 familyMessageRepositoryV2;

    @Autowired
    private StudentServiceV2 studentServiceV2;

    // 保存家庭信息，基于学生ID查找学生并处理家庭信息
    // 如果已经存在相同的家长信息，则更新现有记录，否则插入新记录
    public FamilyMessage saveFamilyMessage(FamilyMessage familyMessage, UUID studentId) {
        Student student = studentServiceV2.findById(studentId)
            .orElseThrow(() -> new RuntimeException("未找到对应的学生"));
        familyMessage.setStudent(student);

        // 检查是否已经存在相同的家长信息
        List<FamilyMessage> existingFamilyMessages = familyMessageRepositoryV2.findByStudent(student);
        if (!existingFamilyMessages.isEmpty()) {
            FamilyMessage existingFamilyMessage = existingFamilyMessages.get(0);
            // 更新现有记录
            existingFamilyMessage.setFatherName(familyMessage.getFatherName());
            existingFamilyMessage.setMotherName(familyMessage.getMotherName());
            existingFamilyMessage.setFatherPhone(familyMessage.getFatherPhone());
            existingFamilyMessage.setMotherPhone(familyMessage.getMotherPhone());
            existingFamilyMessage.setHomeAddress(familyMessage.getHomeAddress());
            return familyMessageRepositoryV2.save(existingFamilyMessage);
        } else {
            // 插入新记录
            return familyMessageRepositoryV2.save(familyMessage);
        }
    }

    // 根据ID获取家庭信息
    public FamilyMessage getFamilyMessageById(Long id) {
        return familyMessageRepositoryV2.findById(id).orElse(null);
    }

    // 获取所有家庭信息
    public List<FamilyMessage> getAllFamilyMessages() {
        return familyMessageRepositoryV2.findAll();
    }

    // 更新家庭信息
    public FamilyMessage updateFamilyMessage(FamilyMessage familyMessage) {
        return familyMessageRepositoryV2.save(familyMessage);
    }

    // 删除家庭信息
    public void deleteFamilyMessage(Long id) {
        familyMessageRepositoryV2.deleteById(id);
    }

    // 根据关键词搜索家庭信息
    public List<FamilyMessage> searchFamilyMessages(String keyword) {
        return familyMessageRepositoryV2.findByKeyword(keyword);
    }

    // 根据学生ID获取家庭信息
    public List<FamilyMessage> getFamilyMessagesByStudentId(UUID studentId) {
        return familyMessageRepositoryV2.findByStudentId(studentId);
    }
}